<template>
  <div>
    <van-form @submit="bookTypeOnSubmit">
      <van-cell-group inset>
        <van-field
          v-model="bookForm.name"
          input-align="right"
          label="书名"
          placeholder="请输入书名"
        />
        <van-field
          v-model="bookForm.isbn"
          input-align="right"
          label="ISBN号码"
          placeholder="请输入ISBN 号码"
        />
        <van-field
          v-model="bookForm.author"
          input-align="right"
          label="作者"
          placeholder="请输入作者"
        />
        <van-field
          v-if="route.query.model == 4"
          v-model="bookForm.dynasty"
          input-align="right"
          label="朝代"
          placeholder="请输入朝代"
        />

        <van-field
          v-model="bookForm.country"
          input-align="right"
          label="国家"
          placeholder="请输入国家"
        />
        <van-field
          v-model="parentIdModel"
          input-align="right"
          is-link
          readonly
          name="picker"
          label="书目类别"
          placeholder="点击选择书目类别"
          @click="parentOnChange"
        />
        <van-cell-group inset>
          <van-field
            style="padding: 20px 0"
            v-model="bookForm.summary"
            label-align="top"
            rows="4"
            autosize
            label="内容摘要"
            type="textarea"
            maxlength="500"
            placeholder="请输入内容摘要"
            show-word-limit
          />
        </van-cell-group>
        <van-popup v-model:show="parentIdShowPicker" position="bottom">
          <van-picker
            :columns="state.parentColumns"
            :columns-field-names="customFieldName"
            @confirm="parentOnConfirm"
            @cancel="parentOnCancel"
          />
        </van-popup>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { useAppStore, useUserStore } from "../../../stores";
import { computed, onMounted, reactive, ref, toRefs, watch } from "vue";

import {
  AddBook,
  editBook,
  getBookListSelect,
  getBookTypeListForTree,
  getBookInfo,
} from "@/service/book";
import { useRoute, useRouter } from "vue-router";
import { showToast, showSuccessToast } from "vant";

const appStore = useAppStore();
const userStore = useUserStore();

const router = useRouter();
const route = useRoute();
const currentBooTypeGroup = ref([]);

const form = reactive({
  bookForm: {
    name: "", // 书名
    isbn: "", // ISBN 号码
    summary: "", // 内容 摘要
    author: "", // 作者
    dynasty: "", // 朝代
    country: "", // 国家
    bootType: null, // 书的类别 bootType的查询
    type: null, //	大类别 先写死 1.英语 2.数学 3.汉字, 4.古诗
    cUserId: null, //用户ID
  },
});

const { bookForm } = toRefs(form);

const parentIdShowPicker = ref(false);

onMounted(() => {
  if (route.name == "libraryEdit") {
    bookDetail(route.query.id);
  }
});

const bookDetail = async (id) => {
  const { data } = await getBookInfo({ id });
  bookForm.value = data;
};

const parentIdModel = ref("");
watch(currentBooTypeGroup, () => {
  parentIdModel.value =
    currentBooTypeGroup.value.length &&
    currentBooTypeGroup.value.map((item) => item.name).join("/");
  console.log(parentIdModel.value);
});

const state = reactive({
  typeColumns: [
    { text: "英语", value: 1 },
    { text: "数学", value: 2 },
    { text: "语文", value: 3 },
    { text: "古诗", value: 4 },
  ],
  parentColumns: [],
});

const typeShowPicker = ref(false);
const typeOnChange = (e) => {
  typeShowPicker.value = true;
};

const typeOnConfirm = ({ selectedOptions }) => {
  bookForm.value.type = selectedOptions[0]?.value;
  typeShowPicker.value = false;
};

const typeOnCancel = (e) => {
  typeShowPicker.value = false;
};

const parentOnChange = () => {
  parentIdShowPicker.value = true;
};

const parentOnConfirm = ({ selectedOptions }) => {
  currentBooTypeGroup.value = selectedOptions;
  bookForm.value.bootType = selectedOptions[selectedOptions.length - 1]?.id;
  parentIdShowPicker.value = false;
};
const parentOnCancel = (e) => {
  parentIdShowPicker.value = false;
};

const bookTypeOnSubmit = async () => {
  if (route.name == "libraryEdit") {
    const { status } = await editBook({
      ...bookForm.value,
    });
    if (status == 0) {
      showSuccessToast("编辑成功");
      router.go(-1);
    }
  } else {
    const { status } = await AddBook({
      ...bookForm.value,
      ...{ type: route.query.model },
    });
    if (status == 0) {
      showSuccessToast("新增成功");
      router.go(-1);
    }
  }
};

const customFieldName = reactive({
  text: "name",
  value: "id",
  children: "list",
});
const getparentList = async () => {
  const type = route.query.model;
  const { data } = await getBookTypeListForTree({
    type: route.query.model,
  });
  state.parentColumns = removeEmptyLists(data);
};

// 使用递归和对象解构来移除空的 list 字段
const removeEmptyLists = (obj) => {
  if (Array.isArray(obj)) {
    // 如果是数组，递归处理每个元素
    return obj.map((item) => removeEmptyLists(item));
  } else if (typeof obj === "object" && obj !== null) {
    // 如果是对象，使用对象解构来移除空的 list 字段
    const { list, ...rest } = obj;
    return {
      ...rest,
      list: list.length > 0 ? removeEmptyLists(list) : null,
    };
  } else {
    // 其他情况，直接返回
    return obj;
  }
};

getparentList();
</script>

<style scoped></style>
